﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace weba.Sales
{
    public partial class StockOutNoteHeaderEditFromNeedMaterial : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!this.IsPostBack)
            {
                if (Request.QueryString["NeedMaterialID"] != null)
                {
                    if (mk.IsNumber(Request.QueryString["NeedMaterialID"].ToString()))
                    {
                        //用一个隐藏Label保存传递过来的ID
                        this.lblNeedMaterialID.Text = Request.QueryString["NeedMaterialID"].ToString();
                    }
                    else
                    {
                        mk.Alert("参数错误！");
                    }
                }
                else
                {
                    mk.Alert("参数错误！");
                }
                Accounts_Users currentUser = mk.l.Accounts_Users.FirstOrDefault();
                //设置根部门ID
                var bllDept = mk.l.Accounts_Department.ToList();
                this.lblRootDepartmentID.Text = bllDept.Where(j => j.ClassID == (int.Parse(currentUser.DepartmentID))).FirstOrDefault().RootID.ToString();

                //绑定页面基本数据
                this.BindData();
                //给日期输入框添加只读属性，不能在属性里直接设置，不然会取不到值
                this.txtDateStockOut.Attributes["readonly"] = "true";
            }
        }
    private void BindData()
        {
            var bllNeedHeader = mk.l.Sales_NeedMaterialHeader.ToList();
          Sales_NeedMaterialHeader mNeedHeader = bllNeedHeader.Where(h=>h.NeedMaterialID==int.Parse(this.lblNeedMaterialID.Text)).FirstOrDefault();
            if (mNeedHeader != null)
            {
                if (int.Parse(this.lblRootDepartmentID.Text) == mNeedHeader.RootDepartmentID)
                {
                    //先判断一下是否已经提交 没提交的就别管了
                    if (mNeedHeader.StatusSubmit == "2")
                    {
                        this.lblSalesOrderID.Text = mNeedHeader.SalesOrderID.ToString();
                      var bllSalesOrderHeader =mk.l.Sales_SalesOrderHeader.ToList();
                               Sales_SalesOrderHeader mSalesOrderHeader = bllSalesOrderHeader.Where(h=>h.SalesOrderID==mNeedHeader.SalesOrderID).FirstOrDefault();
                        if (mSalesOrderHeader != null)
                        {
                            this.BindMaterialCategoryID();
                            //先判断指定订单有无出库单，如没有，添加之，如有，显示之
                       var bllStockHeader = mk.l.Sales_StockOutNoteHeader.ToList();
                            if (bllStockHeader.Where(y=>y.NeedMaterialID==(int.Parse(this.lblNeedMaterialID.Text))).Count()>0)
                            {
                                this.ShowData();
                            }
                            else
                            {
                                this.AddStockNoteHeaderAndDetail();
                                this.ShowData();
                            }
                        }
                        else
                        {
                           mk.Alert("此用料单尚未提交！");
                        }
                    }

                    else
                    {
                       mk.Alert("参数错误！");
                    }
                }
                else
                {
                   mk.Alert("只能操作本店的订单！");
                }
            }
            else
            {
               mk.Alert("参数错误！");
            }
        }

        /// <summary>
        /// Binds the material category ID.绑定材料类型单选列表
        /// </summary>
        private void BindMaterialCategoryID()
        {
           var bll = mk.l.Sales_MaterialCategory.ToList();
           var ds = bll.ToList();
            this.rbtnlMaterialCategoryID.DataSource = ds;
            this.rbtnlMaterialCategoryID.DataTextField = "Name";
            this.rbtnlMaterialCategoryID.DataValueField = "MaterialCategoryID";
            this.rbtnlMaterialCategoryID.DataBind();
        }

        /// <summary>
        /// Adds the stock note header and detail.添加新的出库单及明细
        /// </summary>
        private void AddStockNoteHeaderAndDetail()
        {
          var bllStockHeader =mk.l.Sales_StockOutNoteHeader.ToList();
            //添加新的出库单
      Sales_StockOutNoteHeader  mStockHeader = new Sales_StockOutNoteHeader();
            //获取当前用户信息
         Accounts_Users currentUser = mk.l.Accounts_Users.FirstOrDefault();
         var bllOrderHeader =mk.l.Sales_SalesOrderHeader.ToList();
                   Sales_SalesOrderHeader mOrderHeader = bllOrderHeader.Where(h=>h.SalesOrderID==int.Parse(this.lblSalesOrderID.Text)).FirstOrDefault();
            mStockHeader.DateStockOut = System.DateTime.Now;
            mStockHeader.Manager = currentUser.UserName;
            mStockHeader.ModifiedDate = System.DateTime.Now;
            mStockHeader.NeedMaterialID = int.Parse(this.lblNeedMaterialID.Text);
            mStockHeader.RootDepartmentID = int.Parse(this.lblRootDepartmentID.Text);
            mStockHeader.SalesOrderID = int.Parse(this.lblSalesOrderID.Text);
            mStockHeader.Status = "1";
            //把订货单编号设置成和对应订单的编号相同
            mStockHeader.StockOutNoteNumber = mOrderHeader.SalesOrderNumber;
            //添加新的出库单 保存其ID
            mk.l.Sales_StockOutNoteHeader.InsertOnSubmit(mStockHeader);
            mk.l.SubmitChanges();
            this.lblStockOutNoteID.Text = mStockHeader.StockOutNoteID.ToString();
            //根据用料单添加出库单明细
           var bllStockDetail = mk.l.Sales_StockOutNoteDetail.ToList();
         var bllNeedDetail = mk.l.Sales_NeedMaterialDetail.ToList();
       Sales_StockOutNoteDetail mStockDetail = new Sales_StockOutNoteDetail();
    Sales_NeedMaterialDetail mNeedDetail = new Sales_NeedMaterialDetail();
      var ds = bllNeedDetail.Where(y=>y.NeedMaterialID.ToString()== this.lblNeedMaterialID.Text).ToList();
            //循环添加出库明细
            foreach (var dr in ds)
            {
                mNeedDetail = bllNeedDetail.Where(h=>h.DetailID==int.Parse(dr.DetailID.ToString())).FirstOrDefault();
                if (mNeedDetail != null)
                {
                    mStockDetail = new Sales_StockOutNoteDetail();
                    mStockDetail.DateStockOut = Convert.ToDateTime("9999-1-1");
                    mStockDetail.InventoryManager = string.Empty;
                    mStockDetail.LocationID = 0;
                    mStockDetail.ManufacturerID = mNeedDetail.ManufacturerID;
                    mStockDetail.MaterialID = mNeedDetail.MaterialID;
                    mStockDetail.ModifiedDate = System.DateTime.Now;
                    mStockDetail.Quantity = mNeedDetail.Quantity;
                    mStockDetail.StatusStockOut = "0";
                    mStockDetail.StockOutNoteID = int.Parse(this.lblStockOutNoteID.Text);
                  //  bllStockDetail.Add(mStockDetail);
                    mk.l.Sales_StockOutNoteDetail.InsertOnSubmit(mStockDetail);
                    mk.l.SubmitChanges();
                }
            }
        }

        /// <summary>
        /// Binds the stock note detail.绑定出库单明细列表
        /// </summary>
        private void BindStockNoteDetail()
        {
    var bll = mk.l.Sales_StockOutNoteDetailandSales_Material.ToList();
            var ds = bll.Where(y=>y.StockOutNoteID.ToString()==this.lblStockOutNoteID.Text).ToList();
            this.myGridView.DataSource = ds;
            this.myGridView.DataBind();
        }

        /// <summary>
        /// Shows the data.显示出库单信息
        /// </summary>
        private void ShowData()
        {
            var bll = mk.l.Sales_StockOutNoteHeader.ToList();
       Sales_StockOutNoteHeader m = bll.Single(y=>y.NeedMaterialID==(int.Parse(this.lblNeedMaterialID.Text)));
            if (m != null)
            {
                //显示出库单概况信息
                this.txtStockOutNoteNumber.Text = m.StockOutNoteNumber;
                this.txtDateStockOut.Date = m.DateStockOut;

             //   UART.BLL.Accounts.Accounts_Users bllUser = new UART.BLL.Accounts.Accounts_Users();
        Accounts_Users mUser = mk.l.Accounts_Users.Where(h=>h.UserName==m.Manager).FirstOrDefault();
                this.lblManagerTrueName.Text = mUser.TrueName;
                this.lblManagerUserName.Text = mUser.UserName;
                //绑定出库单明细
                this.lblStockOutNoteID.Text = m.StockOutNoteID.ToString();

                this.BindStockNoteDetail();
                //如果订单已经提交审核，则把两个修改按钮设置为不可见 把关闭按钮设置为可见
                if (m.Status != "1")
                {
                    this.pnlAdd.Visible = false;
                    this.btnOK.Enabled = false;
                    this.btnOK.Visible = false;
                    this.btnSubmit.Enabled = false;
                    this.btnSubmit.Visible = false;
                    this.myGridView.Columns[5].Visible = false;
                   // this.myGridView.Columns[6].Visible = false;
                }
                else
                {
                    this.btnOK.Enabled = true;
                    this.btnOK.Visible = true;
                    this.btnSubmit.Enabled = true;
                    this.btnSubmit.Visible = true;
                }
            }
        }

        /// <summary>
        /// Handles the RowDeleting event of the myGridView control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.Web.UI.WebControls.GridViewDeleteEventArgs"/> instance containing the event data.</param>
        protected void myGridView_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {
      Sales_StockOutNoteDetail bll = mk.l.Sales_StockOutNoteDetail.Single(y=>y.DetailID==int.Parse(this.myGridView.DataKeys[e.RowIndex].Values["DetailID"].ToString()));
            try
            {
                mk.l.Sales_StockOutNoteDetail.DeleteOnSubmit(bll);
               // bll.Delete(int.Parse(this.myGridView.DataKeys[e.RowIndex].Values["DetailID"].ToString()));
                mk.l.SubmitChanges();
                //提交事务
               // ContextUtil.SetComplete();
            }
            catch (Exception ex)
            {
                //撤销事务
             //   ContextUtil.SetAbort();
                this.lblMsg2.Text = "删除错误！错误信息：" + ex.Message;
            }
            this.BindStockNoteDetail();
        }

        /// <summary>
        /// Handles the RowDataBound event of the myGridView control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.Web.UI.WebControls.GridViewRowEventArgs"/> instance containing the event data.</param>
        protected void myGridView_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                //Label lblManufacturerCode = (Label)(e.Row.FindControl("lblManufacturerCode"));
                //UART.BLL.Sales.Manufacturer bllManufacturer = new UART.BLL.Sales.Manufacturer();
                //UART.Model.Sales.Manufacturer mManufacturer = bllManufacturer.Where(h=>h.int.Parse(this.myGridView.DataKeys[e.Row.RowIndex].Values["ManufacturerID"].ToString()));
                //lblManufacturerCode.Text = mManufacturer.ManufacturerCode;

                Label lblMaterialInventory = (Label)(e.Row.FindControl("lblMaterialInventory"));
              var bllInventory = mk.l.Sales_MaterialInventory.ToList();
                lblMaterialInventory.Text = bllInventory.Where(y=>y.MaterialID==int.Parse(this.myGridView.DataKeys[e.Row.RowIndex].Values["MaterialID"].ToString())).Sum(h=>h.Quantity).ToString();

            }
        }

        /// <summary>
        /// Handles the RowEditing event of the myGridView control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.Web.UI.WebControls.GridViewEditEventArgs"/> instance containing the event data.</param>
        protected void myGridView_RowEditing(object sender, GridViewEditEventArgs e)
        {
            this.myGridView.EditIndex = e.NewEditIndex;
            this.BindStockNoteDetail();
        }

        /// <summary>
        /// Handles the RowCancelingEdit event of the myGridView control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.Web.UI.WebControls.GridViewCancelEditEventArgs"/> instance containing the event data.</param>
        protected void myGridView_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
        {
            this.myGridView.EditIndex = -1;
            this.BindStockNoteDetail();
        }

        /// <summary>
        /// Handles the RowUpdating event of the myGridView control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.Web.UI.WebControls.GridViewUpdateEventArgs"/> instance containing the event data.</param>
        protected void myGridView_RowUpdating(object sender, GridViewUpdateEventArgs e)
        {
            if (this.IsValid)
            {
               var bll = mk.l.Sales_StockOutNoteDetail.ToList();
            Sales_StockOutNoteDetail m = bll.Where(h=>h.DetailID==int.Parse(this.myGridView.DataKeys[e.RowIndex].Values["DetailID"].ToString())).FirstOrDefault();
                if (m != null)
                {
                    TextBox txtQuantity = (TextBox)(this.myGridView.Rows[e.RowIndex].FindControl("txtQuantity"));
                    m.Quantity = decimal.Parse(txtQuantity.Text);
                   // bll.Update(m);
                    mk.l.SubmitChanges();
                    
                }
                this.myGridView.EditIndex = -1;
                //重新绑定数据
                this.BindStockNoteDetail();
            }
        }

        /// <summary>
        /// Handles the ServerValidate event of the CustomValidator1 control.
        /// </summary>
        /// <param name="source">The source of the event.</param>
        /// <param name="args">The <see cref="System.Web.UI.WebControls.ServerValidateEventArgs"/> instance containing the event data.</param>
        protected void CustomValidator1_ServerValidate(object source, ServerValidateEventArgs args)
        {
            if (this.myGridView.Rows.Count > 0)
            {
                args.IsValid = true;
            }
            else
            {
                args.IsValid = false;
            }
        }

        /// <summary>
        /// Handles the Click event of the btnOK control.保存修改
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        protected void btnOK_Click(object sender, EventArgs e)
        {
            if (this.IsValid)
            {
              var bll = mk.l.Sales_StockOutNoteHeader.ToList();
               Sales_StockOutNoteHeader m = bll.Where(h=>h.StockOutNoteID==int.Parse(this.lblStockOutNoteID.Text)).FirstOrDefault();
                m.DateStockOut = Convert.ToDateTime(this.txtDateStockOut.Date);
                m.StockOutNoteNumber = mk.InputText(this.txtStockOutNoteNumber.Text, 30);
                try
                {
                   // bll.Update(m);
                    mk.l.SubmitChanges();
                    //提交事务
                  //  ContextUtil.SetComplete();
                   mk.Alert("出库单明细修改成功！");
                }
                catch (Exception ex)
                {
                    //撤销事务
                 //   ContextUtil.SetAbort();
                   mk.Alert("出库单明细修改失败！错误信息：" + ex.Message);
                }
            }
        }

        /// <summary>
        /// 保存出库单修改并流转到财务部门审核
        /// </summary>
        protected void btnSubmit_Click(object sender, EventArgs e)
        {
            if (this.IsValid)
            {
                //使用StockOutNoteHeader业务逻辑类得到出库单实体类
                var bll =
                           mk.l.Sales_StockOutNoteHeader.ToList();
            Sales_StockOutNoteHeader m = 
                    bll.Where(h=>h.StockOutNoteID==int.Parse(this.lblStockOutNoteID.Text)).FirstOrDefault();
                if (m != null)
                {
                    if (m.Status == "1")   //如果为未出库状态
                    {
                        //得到出库日是期 
                        m.DateStockOut = Convert.ToDateTime(this.txtDateStockOut.Date);
                        //出库单编号
                        m.StockOutNoteNumber = mk.InputText
                            (this.txtStockOutNoteNumber.Text, 30);
                        //设置订单的状态为提交审核
                        m.Status = "2";
                        try
                        {
                            mk.l.SubmitChanges();
                          //  bll.Update(m);            //提交出库单更改
                          //  ContextUtil.SetComplete();//提交事务
                           mk.Alert("出库单提交成功！");
                        }
                        catch (Exception ex)
                        {
                            //撤销事务
                         //   ContextUtil.SetAbort();
                           mk.Alert("出库单提交失败！错误信息：" + ex.Message);
                        }
                    }
                    else
                    {
                       mk.Alert("此出库单已提交或已出库！");
                    }
                }
                else
                {
                   mk.Alert("参数错误！");
                }
            }
        }

        /// <summary>
        /// Handles the TextChanged event of the txtName control.输入材料货号后，查询材料表中有无此种材料，如有，自动显示厂家代码和材料类型
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        protected void txtName_TextChanged(object sender, EventArgs e)
        {
            string strMaterialName = mk.InputText(this.txtName.Text, 50);
            var bll = mk.l.Sales_Material.ToList();

            Sales_Material m = bll.Where(h=>h.Name==strMaterialName).FirstOrDefault();
            if (m != null)
            {
                this.rbtnlMaterialCategoryID.Items.FindByValue(m.MaterialCategoryID.ToString()).Selected = true;
                //UART.BLL.Sales.Manufacturer bllM = new UART.BLL.Sales.Manufacturer();
                //UART.Model.Sales.Manufacturer mM = bllM.Where(h=>h.m.ManufacturerID);
                //if (mM != null)
                //{
                //    this.txtManufacturerCode.Text = mM.ManufacturerCode;
                //}
            }
        }

        /// <summary>
        /// Handles the ServerValidate event of the CustomValidator2 control.验证是否存在厂家
        /// </summary>
        /// <param name="source">The source of the event.</param>
        /// <param name="args">The <see cref="System.Web.UI.WebControls.ServerValidateEventArgs"/> instance containing the event data.</param>
        protected void CustomValidator2_ServerValidate(object source, ServerValidateEventArgs args)
        {
           
        }

        /// <summary>
        /// Handles the Click event of the btnAddProduct control.添加材料信息 更新订单概况
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        protected void btnAddProduct_Click(object sender, EventArgs e)
        {
            if (this.IsValid)
            {
               var bllStockDetail =mk.l.Sales_StockOutNoteDetail.ToList();
          Sales_StockOutNoteDetail mStockDetail = new   Sales_StockOutNoteDetail();

                try
                {
                    //先根据厂家代码取得厂家ID
                    //UART.BLL.Sales.Manufacturer bllManufacturer = new UART.BLL.Sales.Manufacturer();
                    //UART.Model.Sales.Manufacturer mManufacturer = bllManufacturer.Where(h=>h.mk.InputText(this.txtManufacturerCode.Text, 20));
                    //int intMaterialID = 0;
                    //判断材料列表中有无此种材料 如果没有 则添加之
                    //string strName = mk.InputText(this.txtName.Text, 50);
                    //int intMaterialCategoryID = int.Parse(this.rbtnlMaterialCategoryID.SelectedValue);

                    //UART.BLL.Sales.Material bllMaterial = new UART.BLL.Sales.Material();
                    //UART.Model.Sales.Material mMaterial = new UART.Model.Sales.Material();
                    //if (!bllMaterial.Exists(intMaterialCategoryID, mManufacturer.ManufacturerID, strName))
                    //{
                    //    mMaterial.ManufacturerID = mManufacturer.ManufacturerID;
                    //    mMaterial.MaterialCategoryID = intMaterialCategoryID;
                    //    mMaterial.Name = strName;
                    //    intMaterialID = bllMaterial.Add(mMaterial);
                    //}
                    //else
                    //{
                    //    mMaterial = bllMaterial.Where(h=>h.intMaterialCategoryID, mManufacturer.ManufacturerID, strName);
                    //    intMaterialID = mMaterial.MaterialID;
                    //}

                    var bllMaterial = mk.l.Sales_Material.ToList();
             Sales_Material mMaterial = bllMaterial.Where(h=>h.MaterialCategoryID==int.Parse(this.rbtnlMaterialCategoryID.SelectedValue)&h.Name== mk.InputText(this.txtName.Text, 50)).FirstOrDefault();
                    if (mMaterial != null)
                    {
                        mStockDetail.MaterialID = mMaterial.MaterialID;
                    }

                    mStockDetail.DateStockOut = Convert.ToDateTime("9999-1-1");
                    mStockDetail.InventoryManager = string.Empty;
                    mStockDetail.LocationID = 0;
                    mStockDetail.ManufacturerID = mMaterial.ManufacturerID;
                    //mStockDetail.MaterialID = intMaterialID;
                    mStockDetail.ModifiedDate = System.DateTime.Now;
                    mStockDetail.Quantity = decimal.Parse(this.txtQuantity.Text);
                    mStockDetail.StatusStockOut = "0";
                    mStockDetail.StockOutNoteID = int.Parse(this.lblStockOutNoteID.Text);
                    mk.l.Sales_StockOutNoteDetail.InsertOnSubmit(mStockDetail);
                    mk.l.SubmitChanges();
                  //  bllStockDetail.Add(mStockDetail);

                    //绑定订货单明细列表
                    this.BindStockNoteDetail();
                    //把输入框设置为空
                    this.txtName.Text = string.Empty;
                    this.txtQuantity.Text = string.Empty;
                    //this.txtManufacturerCode.Text = string.Empty;
                    //清除选定项
                    this.rbtnlMaterialCategoryID.ClearSelection();
                    //提交事务
                  //  ContextUtil.SetComplete();
                }
                catch (Exception ex)
                {
                    //撤销事务
                  //  ContextUtil.SetAbort();
                    this.lblMsg2.Text = "添加错误！错误信息：" + ex.Message;
                }
            }
        }



    }
}
